package cn.csq.rpc.client;

import cn.csq.rpc.Peer;
import cn.csq.rpc.transport.TransportClient;
import com.csq.rpc.common.utils.ReflectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author csq
 * @version 1.0.0
 * @ClassName RandomTransportSelector.java
 * @Description 随机
 * @createTime 2021年12月20日 23:06:00
 */
@Slf4j
public class RandomTransportSelector implements TransportSelector {
    /**
     * 已经连接好的client
     */
    private List<TransportClient> clients;

    public RandomTransportSelector() {
        clients = new ArrayList<>();
    }

    //可能会出现多线程并发操作可能 加上sync保证多线程安全

    @Override
    public synchronized void init(List<Peer> peers, int count, Class<? extends TransportClient> clazz) {
        count = Math.max(count, 1);
        for (Peer peer : peers) {
            for (int i = 0; i < count; i++) {
                try {
                    TransportClient transportClient = ReflectionUtils.newInstance(clazz);
                    //连接 加入clients
                    transportClient.connect(peer);
                    clients.add(transportClient);
                    log.info("connect server:{}", peer);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public synchronized TransportClient select() {
        //从已经连接好的客户端随机取一个
        int random = new Random().nextInt(clients.size());
        return clients.get(random);
    }

    @Override
    public synchronized void release(TransportClient client) {
        //加入池子中，下一次使用
        clients.add(client);
    }

    @Override
    public  synchronized void close() {
        for (TransportClient client : clients) {
            clients.clear();
        }
        clients.clear();
    }
}
